from datetime import datetime
import requests
import json
import time

openai_key = "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"

openai_url = "https://suancaiyv.cfd/v1/chat/completions"

major = "人工智能技术应用"
title = "人工智能在医疗、智能家居、智能交通领域的应用"

# 设置请求头，包括授权信息

def openai_request(content, modle="gpt-3.5-turbo", max_tokens=1200, temperature=0.9, stop=None):
    headers = {
        "Authorization": f"Bearer {openai_key}",
        "Content-Type": "application/json"
    }
    # 设置请求体，包含提示，引擎，最大令牌数，温度，停止符等参数
    data = {
        "messages":  [
        {
            "role": "system",
            "content": "I want you to act as an academician. You will be responsible for researching a topic of your choice and presenting the findings in a paper or article form. Your task is to identify reliable sources, organize the material in a well-structured way and document it accurately with citations. The entire conversation and instructions should be provided in Chinese."
        },
        {
            "role": "user",
            "content": content
        }
    ],
        "model": modle,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stop": stop
    }
    data = json.dumps(data)
    response = requests.post(openai_url, headers=headers, data=data)
    print("请求成功开始撰写")
    story = response.json()["choices"][0]["message"]["content"]
    return story

##摘要处理
abstract_prompt = f"请按照以下要点撰写{major}专业的论文{title}摘要,要点:S1.摘要应排除本学科领域成为常识的内容。2.不要简单重复标题中有的信息。3.要用第三人称，一般不使用“本文”“本研究”“作者”“笔者”“我们”等词语作为主语。4.一般不要对论文内容做拴释和评论，尤其是自我评价。5.要使用规范化的名词术语，不使用非公知公用的符号和术语，使用新术语需加括号说明；由外文翻泽且尚无汉语术语与之对照的，可用原文或加括号注明原文。6.不要写成背景叙述。7.结构严谨、表达简明、语义确切，注意句子之间的逻辑性，慎用长句、复杂句，每句话表意清晰明确，无空泛、笼统、合混之词。8.内容800字左右"
abstract_ai = openai_request(abstract_prompt,stop=None)
abstract = f"{abstract_ai}"
print(f"已完成“摘要部分”")
time.sleep (22)



#大纲处理，分离出大纲
def ex_outline():
    outline_prompt = f"我想写一篇{major}专业关于{title}的论文，请帮我拟定一份论文大纲。格式:按照二级标题列出提纲。一级标题是中文数字，二级标题是（一）。 格式案例:以下仅仅是一个格式的例子，你写的时候按照这个格式写，但是内容按照你自己的思路写。 一、引言 （一）研究的背景以及意义 （二）…"
    outline_ai = openai_request(outline_prompt,stop=None)
    time.sleep (60)
    outline_text = f"\"\"\"{outline_ai}\"\"\""
    outline = [] 
    lines = outline_text.split("\n")
    for line in lines:
        if line.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "1", "2", "3", "4", "5", "6", "（" ,"）", "(", ")")):
            outline.append(line)
        else:
            continue
    outline = "\n".join(outline)
    return outline


def body():
    outline_ex = ex_outline() #论文大纲
    outline_list = outline_ex.split("\n") # 将大纲分割成列表
    # 初始化一个空字符串，用于存储正文内容
    content_list = ""
    for item in outline_list:
        if item.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十")):
            content_list += f"{item}\n"
            time.sleep (22)
        elif item.startswith(("（", "）", "(", ")")):
            content_prompt =f"我希望你能扮演一名{major}专业博士生导师的角色撰写论文。我会给你写作主题。写作主题 ：{title}，论文提纲为:'{outline_ex}'以下是写作要求：1. 你创作的内容需要符合学术规范，逻辑严密。不要有冗余的信息。2. 创作的内容需要符合中文的叙述规范。3.紧扣写作主题，不要偏离写作主题4.模拟人类的表达习惯，不要使用ai的思维5.{item}为二级标题注意文章结构规范。以下是我的输入：请撰写:'{item}'"
            content_ai = openai_request(content_prompt,stop=None)
            content = f"{content_ai}"
            content_list += f"{item}\n{content}\n"
            print(f"已完成{item}")
            time.sleep (60)
    return content_list

body_text = f"{body()}"
print (body_text)

#生成论文内容
paper = []
paper.append(title + '\n' + abstract + '\n' + body_text + '\n')
print(paper)



current_time = datetime.now()
timestamp = current_time.strftime("%Y%m%d%H%M%S")
file_name = f"{timestamp}.txt"

# 打开文件并以UTF-8编码写入文本内容
with open(file_name, 'w', encoding='utf-8') as file:
    file.write('\n'.join(paper))

print(f"文件 '{file_name}' 已创建并写入内容。")